package cn.chinaflame.pagodas.utils.stl;

import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
* Json工具类
* JsonUtil.class
* @author lihexiao
* @create 2017-03-02 14:30 www.hnapay.com Inc.All rights reserved.
**/
public class JsonUtil {
    /**
     * 将json字符串转换为map
     * @param json
     * @return
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    public static Map<String, Object> jsonToMap(String json) throws JsonParseException, JsonMappingException,
            IOException
    {
        if (StringUtils.isBlank(json)) {
            return null;
        }

        Map<String, Object> model = new HashMap<String, Object>();
        ObjectMapper mapper = new ObjectMapper();

        model = mapper.readValue(json, Map.class);

        return model;
    }
    
    /**
	 * 把对象转换成Json字符串。
	 * @param obj 需要转换的对象。
	 * @return 转换好的字符串。如果出错会抛出RuntimeException
	 */
	public static String toJSonString(Object obj){
		ObjectMapper mapper = new ObjectMapper();
		StringWriter out = new StringWriter();
		
		try {
			JsonGenerator gen = new JsonFactory().createJsonGenerator(out);
			gen.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
			mapper.setDateFormat(new SimpleDateFormat(DateUtils.DEFAULT_PATTERN));
			mapper.writeValue(gen, obj);
			gen.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return out.toString();
	}
}
